package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Additive;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Foodbatchadditive;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("FoodbatchadditiveService")
@Transactional

public class FoodbatchadditiveServiceImpl extends CmiEmaService implements FoodbatchadditiveService {
	public FoodbatchadditiveServiceImpl() {
	}

	@Transactional
	public Foodbatchadditive saveFoodbatchadditive(Foodbatchadditive foodbatchadditive) {

		if (foodbatchadditive.getId() == null) {
			Additive additive = additiveDAO.findAdditiveById(foodbatchadditive.getAdditive().getId());
			Foodbatch foodbatch = foodbatchDAO.findFoodbatchById(foodbatchadditive.getFoodbatch().getId());

			Foodbatchadditive existingFoodbatchadditive = foodbatchadditiveDAO
					.findFoodbatchadditiveByPhysicalPrimaryKey(foodbatch.getId(), additive.getId(),
							foodbatchadditive.getContent());

			foodbatchadditive.setAdditive(additive);
			foodbatchadditive.setFoodbatch(foodbatch);

			if (isEquals(foodbatchadditive, existingFoodbatchadditive)) {
				return existingFoodbatchadditive;
			}

			foodbatchadditive = foodbatchadditiveDAO.store(foodbatchadditive);
			foodbatchadditiveDAO.flush();

		} else {
			Foodbatchadditive existingFoodbatchadditive = foodbatchadditiveDAO
					.findFoodbatchadditiveByPrimaryKey(foodbatchadditive.getId());

			foodbatchadditive = foodbatchadditiveDAO.store(foodbatchadditive);
			foodbatchadditiveDAO.flush();
		}

		return foodbatchadditive;
	}

	public void deleteFoodbatchadditive(Foodbatchadditive foodbatchadditive) {
		foodbatchadditiveDAO.remove(foodbatchadditive);
		foodbatchadditiveDAO.flush();
	}

	@Transactional
	public void deleteFoodbatchadditives(Set<Integer> deleteFoodbatchadditivesId) {
		Query query = foodbatchadditiveDAO.createNamedQuery("deleteFoodbatchadditivesById", -1, -1);
		query.setParameter(1, deleteFoodbatchadditivesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodbatchadditive> loadFoodbatchadditives() {
		return foodbatchadditiveDAO.findAllFoodbatchadditives();

	}

	@Transactional
	public Set<Foodbatchadditive> loadReferenceFoodbatchadditives(Set<Foodbatchadditive> foodbatchadditives) {
		Iterator<Foodbatchadditive> foodbatchadditivesIterator = foodbatchadditives.iterator();
		Set<Foodbatchadditive> referencedFoodbatchadditives = new HashSet<>();
		while (foodbatchadditivesIterator.hasNext()) {
			Foodbatchadditive currentFoodbatchadditive = foodbatchadditivesIterator.next();

		}
		return referencedFoodbatchadditives;
	}

	public Set<Foodbatchadditive> loadFoodbatchadditivesByIdSet(Set<Integer> foodbatchadditiveIdSet) {

		Iterator<Integer> foodbatchadditiveIdIterator = foodbatchadditiveIdSet.iterator();
		Set<Foodbatchadditive> foodbatchadditiveSet = new HashSet<>();
		while (foodbatchadditiveIdIterator.hasNext()) {
			Integer id = foodbatchadditiveIdIterator.next();
			Foodbatchadditive currentFoodbatchadditive = foodbatchadditiveDAO.findFoodbatchadditiveById(id);
			foodbatchadditiveSet.add(currentFoodbatchadditive);
		}
		return foodbatchadditiveSet;
	}

	@Transactional
	public List<Foodbatchadditive> findAllFoodbatchadditives(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodbatchadditive>(
				foodbatchadditiveDAO.findAllFoodbatchadditives(startResult, maxRows));
	}

	@Transactional
	public Foodbatchadditive findFoodbatchadditiveByPrimaryKey(Integer id) {
		return foodbatchadditiveDAO.findFoodbatchadditiveByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodbatchadditives() {
		return ((Long) foodbatchadditiveDAO.createQuerySingleResult("select count(o) from Foodbatchadditive o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodbatchadditives(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodbatchadditive.class);
		return ((Long) foodbatchadditiveDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countFoodbatchadditivesByName(String queryName) {
		Query query = foodbatchadditiveDAO.createNamedQuery("countFoodbatchadditivesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodbatchadditivesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodbatchadditive.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodbatchadditiveObjectReferencedSet(Foodbatchadditive foodbatchadditive) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodbatchadditive.getAdditive() != null) {

			Set<Integer> additiveIds = new HashSet<Integer>();
			additiveIds.add(foodbatchadditive.getAdditive().getId());
			objectReferencedSetMap.put("additiveIds", additiveIds);
		}
		if (foodbatchadditive.getFoodbatch() != null) {

			Set<Integer> foodbatchIds = new HashSet<Integer>();
			foodbatchIds.add(foodbatchadditive.getFoodbatch().getId());
			objectReferencedSetMap.put("foodbatchIds", foodbatchIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodbatchadditiveClassReferencedSet(Foodbatchadditive foodbatchadditive) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("additives", additiveDAO.findAllAdditives());
		classReferencedSetMap.put("foodbatchs", foodbatchDAO.findAllFoodbatchs());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodbatchadditive foodbatchadditive, Object obj) {
		if (obj == foodbatchadditive)
			return true;
		if (!(obj instanceof Foodbatchadditive))
			return false;
		Foodbatchadditive comparedFoodbatchadditive = (Foodbatchadditive) obj;
		if (!CheckPropertyEqual(foodbatchadditive.getFoodbatch().getId(),
				comparedFoodbatchadditive.getFoodbatch().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodbatchadditive.getAdditive().getId(),
				comparedFoodbatchadditive.getAdditive().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodbatchadditive.getContent(), comparedFoodbatchadditive.getContent())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

